package main

import (
	"chainproxy/log"
	"crypto/md5"
	"encoding/hex"
	"io/ioutil"
	"os"
	"path"
)

func exists(p string) bool {
	_, err := os.Stat(p)
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

func md5str(src string) string {
	ctx := md5.New()
	ctx.Write([]byte(src))
	return hex.EncodeToString(ctx.Sum(nil))
}

// 将 github.com/gin-contrib/sse 这种，转换成 xxxxxxmd5
func getPathModName(modname string) string {
	return md5str(modname)
}

// addFile 将文件存入对应目录
func addFile(modname, version, filetype string, data []byte) (string, error) {
	var err error
	dirName := path.Join(getRoot(), "ver", getPathModName(modname))
	if !exists(dirName) {
		err = os.MkdirAll(dirName, os.ModePerm)
		if err != nil {
			log.Logger.Error("mkdir all failed.", err.Error())
			return "", err
		}
	}
	fname := version + filetype
	fullPath := path.Join(dirName, fname)
	log.Logger.Info("cache file ", fname)
	return fullPath, ioutil.WriteFile(fullPath, data, 0644)
}

func getFile(modname, fname string) ([]byte, error) {
	dirName := path.Join(getRoot(), "ver", getPathModName(modname))
	fullPath := path.Join(dirName, fname)
	return ioutil.ReadFile(fullPath)
}

func isExist(modname, fname string) (string, bool) {
	dirName := path.Join(getRoot(), "ver", getPathModName(modname))
	fullPath := path.Join(dirName, fname)
	return dirName, exists(fullPath)
}